/* global $, visoConfig, Mustache, uuid, jsPlumb */

var faaa = (function() {
	var _thisNode = null;
	var timeoutId = null;
	var areaId = '#folwMain';

	jsPlumb.ready(jsPlumbMain);
	

	// 放入拖动节点
	function dropNode(dataset, ui, obj) {
		var dataObj = ui.position;
		var left = parseInt(ui.offset.left - $(obj).offset().left);
		var top = parseInt(ui.offset.top - $(obj).offset().top);
		dataObj.id = uuid.v1();
		dataObj.top = top;
		dataObj.left = left;
		dataObj.jnode = dataset.jnode;
		dataObj.jnodeClass = dataset.jnodeClass;
		dataObj.jnodeHtml = ui.helper.html();
		console.log("《跟踪》创建节点：template.dataObj", dataObj);
		var targetHtml = renderHtml(dataset.template, dataObj);
		$(areaId).append(targetHtml); //追加元素

		initSetNode(dataObj); // 初始化节点设置
	}

	// 初始化节点设置
	function initSetNode(dataObj) {
		var id = dataObj.id;
		// jsPlumb.draggable(id, {containment: 'parent'})
		addDraggable(id);

		var isvisible = false;
		if("judge" == dataObj.jnode) {
			isvisible = true; //判断节点显示Label标签
		}
		//设置四周端点
		visioConfig.baseArchors.forEach(function(key) {
			jsPlumb.addEndpoint(
				id, {
					anchors: key,
					connectorOverlays: [
						["Arrow", {
							width: 10,
							length: 10,
							location: 1,
							id: "arrow",
							visible: isvisible
						}],
						["Label", {
							label: "条件",
							id: "myLabel",
							cssClass: "connectorLabel",
							visible: isvisible,
							events: {
								"click": function(label, evt) {
									console.log("clicked on label for connection", label.component);
								}
							}
						}]
					]
				},
				visioConfig.hollowCircle);
		});
		
		//新增可删除的close元素
		$("#" + id).on("dblclick", ".jnode-box", function(conn, originalEvent) {
			clearTimeout(timeoutId); 
			var obj = $(this);
			//下面写双击事件要执行的代码
			if(confirm("确定要删除节点的相关连线吗？")) {
				var id=obj.parent().attr("id");
				jsPlumb.removeAllEndpoints(id);
				//设置四周端点
				visioConfig.baseArchors.forEach(function(key) {
					jsPlumb.addEndpoint(
						id, {
							anchors: key,
							connectorOverlays: [
								["Arrow", {
									width: 10,
									length: 10,
									location: 1,
									id: "arrow",
									visible: isvisible
								}],
								["Label", {
									label: "条件",
									id: "myLabel",
									cssClass: "connectorLabel",
									visible: isvisible,
									events: {
										"click": function (label, evt) {
											console.log("clicked on label for connection", label.component);
										}
									}
								}]
							]
						},
						visioConfig.hollowCircle);
				});
				// obj.parent().remove();
			}
			
		})/*.on("click", ".jnode-box", function(conn, originalEvent) {
			clearTimeout(timeoutId);
			_thisNode = $(this);
			timeoutId = window.setTimeout(function (){
				$("input[name='nodeTitle']").val(_thisNode.text().replace(/"/g,"'").replace(/[\t\n]/g,""))
				$(".nodeTitle").show();
			},300);
		});*/
	}

	// 让元素可拖动
	function addDraggable(id) {
		jsPlumb.draggable(id, {
			containment: 'parent'
		});
	}

	// 利用mustache模板工具，渲染html
	function renderHtml(templateId, dataObj) {
		return Mustache.render($("#" + templateId).html(), dataObj);
	}

	//初始化连接线的文本。
	function initConnection(connection) {
		var labelText = connection.sourceId.substring(15) + "-" + connection.targetId.substring(15);
		var startText = connection.source.innerText;
		var endText = connection.target.innerText;
		labelText = startText + "->" + endText;
		connection.getOverlay("myLabel").setLabel(labelText);
	}

	// 主要入口
	function jsPlumbMain() {
		jsPlumb.setContainer('diagramContainer-main');
		
		//双点击了连接线, 支持删除连线
		jsPlumb.bind('dblclick', function(conn, originalEvent) {
			if(confirm("确定要删除此连线吗？")) {
				console.log("《跟踪》删除连线：", conn);
				jsPlumb.detach(conn)
			}
		});

		jsPlumb.bind("connection", function(connInfo, originalEvent) {
			console.log("《跟踪》成功链接节点：", connInfo.connection);
			initConnection(connInfo.connection);
		});

		jsPlumb.bind("connectionDrag", function(connection) {
			console.log("《跟踪》开始链接节点：", connection);
		});

		jsPlumb.bind("connectionDragStop", function(connection) {
			console.log("《跟踪》结束链接节点：", connection);
		});

		//定义可拖拽控件
		$('.jnode-box').draggable({
			helper: 'clone',
			scope: 'ss'
		});

		//定义可拖拽释放
		$(areaId).droppable({
			scope: 'ss',
			drop: function(event, ui) {
				//创建新节点
				dropNode(ui.draggable[0].dataset, ui, $(this));
			}
		});
	}
	function buildNodeData(node,addFlag){
		console.log("node：", node);
		var blockClass = "jnode-task bdc-primary";
		var layerArr=[];
		var BlockY=150;
		var BlockX=500;
		var BlockJnode = "task";
		for(let i = 0;i<node.length;i++){
			var dataObj;
			if(addFlag){
				dataObj = { top: 50, left: i*250, id: node[i].id+"", jnode: BlockJnode, jnodeClass: blockClass, jnodeHtml: "<span>"+node[i].jobDesc+"</span>" }
			}else{
				if(!layerArr[node[i].layer-1]){
					layerArr[node[i].layer-1]=1;
				}else{
					layerArr[node[i].layer-1]++;
				}
				// dataObj = { top: node[i].layer*BlockY, left: layerArr[node[i].layer-1]*BlockX+(node[i].layer%2)*250, id: node[i].id+"", jnode: BlockJnode, jnodeClass: blockClass, jnodeHtml: "<span>"+node[i].jobDesc+"</span>" }
				dataObj = { top: node[i].blockY?node[i].blockY:node[i].layer*BlockY, left: node[i].blockX?node[i].blockX:layerArr[node[i].layer-1]*BlockX+(node[i].layer%2)*250, id: node[i].id+"", jnode: BlockJnode, jnodeClass: blockClass, jnodeHtml: "<span>"+node[i].jobDesc+"</span>" }
			}
			var targetHtml = renderHtml("jnode-template", dataObj);
			$('#folwMain').append(targetHtml); //追加元素
			initSetNode(dataObj);
		}
	}
	function buildEdgeData(edges){
		console.log("ligature：", edges);
		// 将节点的连线还原
		var PageSourceAnchor = "Bottom";
		var PageTargetAnchor = "Top";
		for(let i = 0;i<edges.length;i++){
			jsPlumb.ready(function (){
				jsPlumb.connect(
					{
						source:edges[i].from+"",
						target:edges[i].to+"",
						anchor: [PageSourceAnchor, PageTargetAnchor],
						paintStyle: { stroke: 'lightgray', strokeWidth: 3 },
						endpointStyle: { fill: 'lightgray', outlineStroke: 'darkgray', outlineWidth: 2 },
						overlays: [ ['Arrow', { width: 12, length: 12, location: 1 }] ]
					},
					visioConfig.hollowCircle
				);
				jsPlumb.draggable(edges[i].from+"");
				jsPlumb.draggable(edges[i].to+"");
			})
		}
	}

	function buildStorageNode(nodeData){
		// 遍历节点
		if(nodeData){
			let node = JSON.parse(nodeData);
			for(let i = 0;i<node.length;i++){
				var blockClass = node[i].BlockClass.replace("jnode-box ","");
				var dataObj = { top: node[i].BlockY, left: node[i].BlockX, id: node[i].BlockId, jnode: node[i].BlockJnode, jnodeClass: blockClass, jnodeHtml: node[i].BlockContent }
				var targetHtml = renderHtml("jnode-template", dataObj);
				$('#folwMain').append(targetHtml); //追加元素
				initSetNode(dataObj);
			}
		}
	}
	function buildStorageEdge(edgeData){
		// 遍历线条
		if(edgeData){
			let ligature = JSON.parse(edgeData);
			// 将节点的连线还原
			for(let i = 0;i<ligature.length;i++){
				jsPlumb.ready(function (){
					jsPlumb.connect(
						{
							source:ligature[i].PageSourceId,
							target:ligature[i].PageTargetId,
							anchor: [ligature[i].PageSourceAnchor, ligature[i].PageTargetAnchor],
							paintStyle: { stroke: 'lightgray', strokeWidth: 3 },
							endpointStyle: { fill: 'lightgray', outlineStroke: 'darkgray', outlineWidth: 2 },
							overlays: [ ['Arrow', { width: 12, length: 12, location: 1 }] ]
						},
						visioConfig.hollowCircle
					);
					jsPlumb.draggable(ligature[i].PageSourceId);
					jsPlumb.draggable(ligature[i].PageTargetId);
				})
			}
		}
	}
	

	
	//页面加载时,获取任务流程图数据
	window.onload = function(){
		$.ajax({
			type : 'POST',
			url : base_url + "/jobNode/getNodes",
			dataType : "json",
			success : function(data){
				if (data.code == 200) {
					//如果有值，则显示上次保存的流程图信息，否则展示后台组装的流程图
					// if(data.content.id){
					// 	jobFlowId = data.content.id;
					// 	buildStorageNode(data.content.nodes);
					// 	buildStorageEdge(data.content.edges);
					// 	//移除的节点信息
					// 	if(data.content.removeIds){
					// 		for (var i=0;i<data.content.removeIds.length;i++){
					// 			jsPlumb.removeAllEndpoints(data.content.removeIds[i]);
					// 			$("#"+data.content.removeIds[i]).remove();
					// 		}
					// 	};
					// 	//增加的节点信息
					// 	if(data.content.nodeJobDTO){
					// 		buildNodeData(data.content.nodeJobDTO.nodes,true);
					// 	}
					// }else{
						jobFlowId = data.content.jobFlowId;
						buildNodeData(data.content.nodes,false);
						buildEdgeData(data.content.edges);
					// }
				}else{
					let options = {icon: 2, time: 2000};
					layer.msg(data.message,options);
				}
			}
		});
	}
	
	/**
	 * 监听按钮点击事件
	 */
	$('body').on('click', '.layui-btn-event', function(e){
		var type = $(this).data('type');
		active[type] ? active[type].call(this, e.target) : '';
	});
	var active = {
		reset: function(e) { /** 重置 */
			location.reload();
		},
		submit: function(e) { /** 提交 */
			// 遍历节点
	    	var blocks = [];
		    $("#folwMain .jnode-box").each(function (idx,elem) {
		        var $elem = $(elem);
		        blocks.push({
		            BlockId: $elem.parent().attr('id'),
		            BlockJnode: $elem.parent().attr('jnode'),
		            BlockContent: $elem.html().replace(/"/g,"'").replace(/[\t\n]/g,""),
		            BlockClass: $elem.attr('class').replace("jnode-box ",""),
		            BlockX: parseInt($elem.parent().css("left"), 10),
		            BlockY: parseInt($elem.parent().css("top"), 10)
		        });
		    });
		    
			// 遍历线条
		    var connects = [];
		    $.each(jsPlumb.getAllConnections(), function (idx,connection) {
		    	var sourceAnchor,targetAnchor;
		    	if(connection.endpoints[0].anchor.type){
		    		// 新增的连线
		    		sourceAnchor = connection.endpoints[0].anchor.type;
		    		targetAnchor = connection.endpoints[1].anchor.type;
		    	}else{
		    		// 原来的连线
		    		sourceAnchor = connection.endpoints[0].anchor.anchors[0].type;
		    		targetAnchor = connection.endpoints[0].anchor.anchors[1].type;
		    	}
		    	connects.push({
		            ConnectionId: connection.id,
		            PageSourceId: connection.sourceId,
		            PageSourceAnchor: sourceAnchor.replace("Middle","").replace("Center",""),
		            PageTargetId: connection.targetId,
		            PageTargetAnchor: targetAnchor.replace("Middle","").replace("Center","")
		        });
		    });

			// 将数据转换格式后存储
		    let ligature = JSON.stringify(connects);
		    // 将多出来的 \ 去掉
		    let node = JSON.stringify(blocks).replace(/\\/g,"");
		    var nodeData={
					id:jobFlowId,
					nodes:node,
					edges:ligature
				};
			$.ajax({
				type : 'POST',
				url : base_url + "/jobNode/saveFlow",
				data: nodeData,
				dataType : "json",
				success : function(data){
					if (data.code == 200) {
						layer.msg(data.msg, {icon: 6});
						location.reload();
					}else{
						let options = {icon: 2, time: 2000};
						layer.msg(data.message||'保存失败',options);
					}
				}
			});
		},
		nodeSubmit: function(e) { 
			// 保存节点标题
			var nodeTitle = $("input[name='nodeTitle']").val();
			_thisNode.find("span").text(nodeTitle);
			var fontSize = 14;
			if(nodeTitle.length<=3){
				fontSize = 14;
			}else if(nodeTitle.length<=5){
				fontSize = 10;
			}else if(nodeTitle.length<=6){
				fontSize = 8;
			}else if(nodeTitle.length<=8){
				fontSize = 6;
			}else{
				fontSize = 5;
			}
			_thisNode.find("span").css("font-size",fontSize+"pt");
		},
		nodeClose: function(e) { 
			// 关闭节点标题
			$(".nodeTitle").hide();
		}
	};
	
})()
